package cn.com.dcsgo.design.pattern.singleton;

import java.io.Serial;
import java.io.Serializable;

/**
 * 单例模式-静态代码块初始化静态属性(实例对象)
 *
 * @author Dcsgo
 * @since 11/9/2025 上午 9:20
 */

public class HungrySingleton2 implements Serializable {
    @Serial
    private static final long serialVersionUID = 1L;
    private final static HungrySingleton2 INSTANCE;

    //静态代码块初始化实例对象
    static {
        INSTANCE = new HungrySingleton2();
    }

    /**
     * 私有化构造方法，不允许new实例化对象
     */
    private HungrySingleton2() {
        if (INSTANCE != null) {
            throw new IllegalStateException("非法创建对象实例");
        }
    }

    public static HungrySingleton2 getInstance() {
        return INSTANCE;
    }

    /**
     * 反序列化时自动回调，保证返回唯一实例
     */
    @Serial
    private Object readResolve() {
        return INSTANCE;
    }
}
